package com.leonzhangxf.web.util.feign.api.github;

import com.leonzhangxf.web.util.feign.api.github.bean.Contributor;
import com.leonzhangxf.web.util.feign.api.github.bean.Repo;
import feign.Feign;
import feign.Param;
import feign.RequestLine;
import feign.gson.GsonDecoder;

import java.util.ArrayList;
import java.util.List;


/**
 * A github api demo.
 *
 * @author leonzhangxf
 * @date 20190429
 */
public interface GitHub {

    /**
     * Get the github api.
     *
     * @return the GitHub api.
     */
    static GitHub getInstance() {
        return Feign.builder()
            .decoder(new GsonDecoder())
            .target(GitHub.class, "https://api.github.com");
    }

    /**
     * Get contributors info list of the target github repository of an owner.
     *
     * @param owner the owner of the target repo.
     * @param repo  the repo willing to query.
     * @return the contributors info list of the repo.
     */
    @RequestLine("GET /repos/{owner}/{repo}/contributors")
    List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);

    /**
     * Get the user's repos.
     *
     * @param owner the owner of the repos.
     * @param sort  sort param.
     * @return the repos of the given user.
     */
    @RequestLine("GET /users/{username}/repos?sort={sort}")
    List<Repo> repos(@Param("username") String owner, @Param("sort") String sort);

    /**
     * Get the user's repos.
     *
     * @param owner the owner of the repos.
     * @return the repos of the given user.
     */
    default List<Repo> reposSortByFullName(String owner) {
        return repos(owner, "full_name");
    }

    /**
     * Lists all contributors for all repos owned by a owner.
     *
     * @param owner the owner of the repos.
     * @return all the contributors contributed to the repos belong to the given owner.
     */
    default List<Contributor> contributorsOfReposOfOwner(String owner) {
        List<Contributor> contributors = new ArrayList<>(3);
        for (Repo repo : this.reposSortByFullName(owner)) {
            contributors.addAll(this.contributors(owner, repo.getName()));
        }
        return contributors;
    }
}
